﻿using DotNetty.Extensions;
using System.Text;

var client = new WebSocketClient("ws://127.0.0.1:8000");

client.OnChannelPipeline += pipeline =>
{
    //心跳
    //pipeline.AddLast(new IdleStateHandler(5, 0, 0));

    //tls证书
    //var cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
    //var targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
    //pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));

};

client.OnConnecting += () =>
{
    Console.WriteLine("Connecting...");
};

client.OnConnected += async () =>
{
    Console.WriteLine("Connected.");

    await client.WriteAndFlushAsync("this is from websocket client text message!");

    var bs = Encoding.UTF8.GetBytes("this is from websocket client binary message!");

    await client.WriteAndFlushAsync(bs);

};

client.OnTextMessage += message =>
{
    Console.WriteLine($"TextMessage==>{message}");
};

client.OnBinaryMessage += message =>
{
    var txt = Encoding.UTF8.GetString(message);
    Console.WriteLine($"BinaryMessage==>{txt}");
};

client.OnException += ex =>
{
    Console.WriteLine($"Exception=>{ex?.Message}");
};

client.OnDisconnected += async () =>
{
    Console.WriteLine("Disconnected.");
    await Task.Delay(2000);
    await client.ConnectAsync(); //reconnect
};

await client.ConnectAsync();

Console.ReadKey();

await client.DisposeAsync();

Console.WriteLine("Hello, World!");